function [ classify_results, class_decision ] = classify( feature_vals, feature_set_name, frames, assoc_classifiers, labels, unknownThreshold )
%COMBINE_FEATURE Summary of this function goes here
%   Detailed explanation goes here

if ~iscell(assoc_classifiers)
    error('Classifiers should be cell.');
end

if ~exist('unknownThreshold', 'var')
    unknownThreshold = 0;
end

assoc_classifiers = build_branches(assoc_classifiers);

classify_results = zeros(size(frames, 2), length(assoc_classifiers), 2);
class_decision = zeros(1, size(frames, 2));
for fid=1:size(frames, 2)
    for cid = 1:length(assoc_classifiers)
        clsfr = assoc_classifiers{cid};
        clsfr_fid = my_find_str(clsfr.features, feature_set_name);
        tmp_fval = feature_vals(fid, clsfr_fid);
        maxclass = 0;
        true_class = 0;
        maxlikelihood = -inf;
        for clsid = 1:length(clsfr.classes)
            tmp_mu = clsfr.feature_val{clsid}.mu;
            tmp_sigma = clsfr.feature_val{clsid}.sigma;
            like = prod(normpdf(tmp_fval, tmp_mu, tmp_sigma));
            if like > maxlikelihood
                maxclass = clsid;
                maxlikelihood = like;
            end
            if frames(3,fid) && any(strcmp(labels{frames(3,fid)}.class, clsfr.classes{clsid}))
                true_class = clsid;
            end
        end
        if(maxlikelihood < unknownThreshold)
            maxclass = 0;
        end
        classify_results(fid, cid, 1) = maxclass;
        classify_results(fid, cid, 2) = true_class;
    end
    
    cur_c = 1;
    while cur_c ~= 0
        class_name = assoc_classifiers{cur_c}.classes(classify_results(fid, cur_c, 1));
        cur_c = assoc_classifiers{cur_c}.branches(classify_results(fid, cur_c, 1));
    end
    class_name = class_name{1};
    for l = 1:length(labels)
        if strcmp(class_name, labels{l}.class)
            class_id = l;
            break;
        end
    end
    class_decision(fid) = class_id;
end

end

function [ idx ] = my_find_str( needle, haystack )

idx = zeros(size(needle));
for i=1:length(needle)
    tmp_idx = find(strcmp(needle{i}, haystack));
    if length(tmp_idx) == 1
        idx(i) = tmp_idx;
    end
end

end

function [ assoc_classifiers ] = build_branches( assoc_classifiers )
    for i=1:length(assoc_classifiers)
        assoc_classifiers{i}.branches = zeros(length(assoc_classifiers{i}.classes),1);
        layer = assoc_classifiers{i}.layer;
        for j=1:length(assoc_classifiers)
            if assoc_classifiers{j}.layer ~= layer+1
                continue;
            end
            for k=1:length(assoc_classifiers{i}.classes)
                if any(strcmp(assoc_classifiers{j}.classes{1}{1}, assoc_classifiers{i}.classes{k}))
                    assoc_classifiers{i}.branches(k) = j;
                end
            end
        end
    end
end

